using System.Data;
using System.Web.Mvc;
using NHibernate;
using NHibernate.Linq;
using Ninject;

namespace Machinery
{
    public class MachineryController : Controller, IPart
    {
        protected bool EnableManualTransactionControl = false;

        #region Machinery Shorthand
        [Inject]
        public IKernel Kernel { get; set; }
        public T Get<T>() { return Kernel.Get<T>(); }
        public ISession Database { get {return Kernel.Get<ISession>();} }
        public INHibernateQueryable<T> DatabaseTable<T>() { return Get<ISession>().Linq<T>(); }
        #endregion
        
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            if (!EnableManualTransactionControl)
                Get<ISession>().BeginTransaction(IsolationLevel.ReadCommitted);
        }

        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            var transaction = Get<ISession>().Transaction;
            if (transaction.IsActive && transaction.WasCommitted == false)
                transaction.Rollback();
            Database.Close();
            base.OnActionExecuted(filterContext);
        }

        protected override void OnException(ExceptionContext filterContext)
        {
            Database.Transaction.Rollback();
            Database.Close();
            base.OnException(filterContext);
        }




    }
}